import { constantRoutes, asyncRoutes } from "@/router";
import layout from "@/layout";
import { tranPermToTreeData } from '@/utils/index';

export default {
  namespaced: true,
  state() {
    return {
      routes: [],
    };
  },
  getters: {},
  mutations: {
    setRoutes(state, data) {
      state.routes = [...constantRoutes, ...data];
    },
  },
  actions: {
    generatorRoutes(context, data) {
      // 菜单权限
      // 处理路由需要的数据解构
      let userAsyncRoute = data.map((item) => {
        let obj = {};
        obj.id = item.id;
        obj.path = item.route;
        obj.parent_id = item.parent_id;
        obj.meta = {
          icon: item.icon,
          title: item.permission_name,
        };
        obj.name = item.permission_mark;
        obj.hidden = item.hidden !== 1;
        if (item.component === "layout") {
          obj.component = layout;
        } else {
          try {
            obj.component = require(`@/views/${item.component}.vue`);
          } catch (error) {
            obj.component = require(`@/views/404.vue`);
          }
        }
        return obj;
      });
      // 整理成树结构
      userAsyncRoute = tranPermToTreeData(userAsyncRoute, 0);
      // console.log(userAsyncRoute);
      userAsyncRoute.push({
        path: "*",
        redirect: "/404",
      });
      context.commit("setRoutes", userAsyncRoute);
      return userAsyncRoute;
    },
  },
};


